<script setup>
import { ref, nextTick, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { createOrderApi } from '@/service/order.js';
import DynamicsForm from '@/components/dynamics-form.vue';
import { categoryPickerApi } from '@/service/goods.js';

const emit = defineEmits(['reload']);

const drawerVisible = ref(false);
const orderFormRef = ref(null);
// 创建一个map来存储所有动态表单的引用
const dynamicFormsRef = ref(new Map());

const generateOrderForm = () => {
    // 使用 nextTick 确保组件已经挂载
    nextTick(() => {
        if (orderFormRef.value) {
            orderFormRef.value.generateForm(null);
        } else {
            console.error('orderFormRef is not ready yet');
        }
    });
}

const getCategoryPicker = async () => {
    const res = await categoryPickerApi();
    categoryList.value = res.data.list;
}

const forms = reactive([]);
const categoryList = ref([]);

const openDrawer = () => {
    drawerVisible.value = true;
    forms.length = 0; // 重置表单
    
    // 使用setTimeout延迟加载表单，避免过早触发验证
    setTimeout(() => {
        // 等待抽屉组件渲染完成后再生成表单
        generateOrderForm();
        getCategoryPicker();
    }, 300);
}

// 设置动态表单的ref
const setFormRef = (el, form) => {
    if (el) {
        dynamicFormsRef.value.set(form.id, el);
    }
}

// 获取特定表单的ref
const getFormRef = (formId) => {
    return dynamicFormsRef.value.get(formId);
}

const changeCategory = async (val) => {
    // 判断是否已经存在
    if (forms.find(form => form.category_id === val)) {
        ElMessage.error('该分类已存在，请勿重复添加');
        return;
    }

    // 获取当前选中的分类
    const category = categoryList.value.find(item => item.id === val);

    // 生成唯一id而不是ref
    const formId = 'category-' + category.id;

    // 添加到forms数组
    forms.push({
        id: formId,  // 使用id而不是ref
        category_id: val,
        category_title: category.title,
        table_name: category.table_name
    });

    // 等待DOM更新后初始化新表单
    nextTick(() => {
        const formRef = getFormRef(formId);
        if (formRef) {
            formRef.generateForm(null);
        }
    });
}

// 移除子表单
const removeForm = (id) => {
    forms.splice(forms.findIndex(form => form.id === id), 1);
}

// 调用所有表单的方法示例
const callAllForms = async () => {
    // 调用主表单
    if (!orderFormRef.value) {
        ElMessage.error('请填写完整的主表单');
        return;
    }

    let formData = {
        main: null,
        product: {}  // 初始化 product 对象
    };

    // 调用主表单
    const mainFormData = await orderFormRef.value.validateForm();
    if (!mainFormData) {
        ElMessage.error('请填写完整的主表单');
        return;
    }

    formData.main = mainFormData;

    // 调用所有动态表单
    for (const form of forms) {
        const formRef = getFormRef(form.id);
        if (formRef) {
            const categoryData = await formRef.validateForm();
            if (!categoryData) {
                ElMessage.error(`请将表单${form.category_title}填写完整`);
                return;
            }
            formData.product[form.category_id] = categoryData;
        }
    }

    // 调用添加订单接口
    createOrderApi(formData).then(({ code, msg }) => {
        if (code === 200) {
            ElMessage.success(msg);
            drawerVisible.value = false;  // 关闭抽屉
            emit('reload');  // 触发重新加载
        } else {
            ElMessage.error(msg);
        }
    });
}

defineExpose({
    openDrawer
})
</script>

<template>
    <el-drawer v-model="drawerVisible" title="新增订单" size="50%">
        <div class="drawer-container">
            <div class="form-container">
                <dynamics-form ref="orderFormRef" table="tk_order" header="订单"></dynamics-form>

                <div v-for="form in forms" :key="form.id" class="dynamic-form">
                    <div class="form-dynamics-header">
                        <div class="left">
                            <span>{{ form.category_title }} 信息</span>
                        </div>
                        <div class="right">
                            <el-button type="danger" icon="Minus" circle @click="removeForm(form.id)" />
                        </div>
                    </div>
                    <dynamics-form :ref="el => setFormRef(el, form)" :table="form.table_name"
                        :header="form.category_title">
                    </dynamics-form>
                </div>

            </div>
        </div>
        <div class="drawer-footer">
            <div class="left">
                <el-select placeholder="添加服务" @change="changeCategory">
                    <el-option v-for="item in categoryList" :key="item.id" :label="item.title"
                        :value="item.id"></el-option>
                </el-select>
            </div>
            <div class="right">
                <el-button type="primary" @click="callAllForms">创建订单</el-button>
            </div>
        </div>
    </el-drawer>
</template>

<style scoped lang="less">
.drawer-container {
    height: calc(100% - 50px);
    overflow-y: auto;
    padding-bottom: 60px;
}

.form-container {
    margin-bottom: 60px;
}

.dynamic-form {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px dashed #e4e7ed;

    .form-dynamics-header {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 10px;
        border-bottom: 1px solid #e4e7ed;
        padding-bottom: 10px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .left {
            flex: 1;
        }

        .right {
            padding: 0 10px;
        }
    }
}

.drawer-footer {
    position: absolute;
    bottom: 0;
    right: 0;
    text-align: right;
    width: 100%;
    padding: 10px 20px;
    box-sizing: border-box;
    border-top: 1px solid #e4e7ed;
    background: white;
    z-index: 10;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .left {
        flex: 0 30%;
    }

    .right {
        flex: 1;
    }
}
</style>